const jwt = require("jsonwebtoken");
const assert = require("http-assert");
const UserModel = require("../models/User");
module.exports = options => {
    return async (req, res, next) => {
        console.log({ originnalUrl: req.originalUrl, method: req.method });
        let token = (req.headers.authorization || "").split(" ").pop();
        assert(token, 401, "请先登录");
        let jwtSignObj = { id: null };
        try {
            jwtSignObj = jwt.verify(token, req.app.get("jwtSecret"));
        } catch (error) {
            assert(false, 401, "请先登录");
        }
        let user = await UserModel.findById(jwtSignObj.id);
        assert(user, 401, "请先登录");
        req.session.user = user;
        next();
    };
};
